using System;
using System.Collections.Generic;
using System.Linq;

namespace MiniStock.Infrastructure
{
    public class Metric
    {
        public string Name { get; set; }

        public Int32 Value { get; set; }
        public Int64 AccumulatedAdd { get; set; }
        public Int64 AccumulatedGet { get; set; }
        public Int64 DeltaAdd { get; set; }
        public Int64 DeltaGet { get; set; }

        public DateTime? StartTime { get; set; }

        public void CopyFrom(Metric source)
        {
            Value = source.Value;
            DeltaAdd = source.AccumulatedAdd - AccumulatedAdd;
            DeltaGet = source.AccumulatedGet - AccumulatedGet;
            
            AccumulatedAdd = source.AccumulatedAdd;
            AccumulatedGet = source.AccumulatedGet;

            if (StartTime == null)
                StartTime = source.StartTime;
        }
    }

    public static class MetricExtender
    {
        public static void Merge(this List<Metric> target, List<Metric> source)
        {
            List<Metric> delete = new List<Metric>();
            target.ForEach(i =>
                               {
                                   var j = source.FirstOrDefault(jj => jj.Name == i.Name);
                                   if (j == null)
                                       delete.Add(i);
                                   else
                                       i.CopyFrom(j);
                                   source.Remove(j);
                               }
                );
            delete.ForEach(i => target.Remove(i));
            target.AddRange(source);
        }
    }
}